/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to marcus@lateralminds.com.au so I can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2008 Lateral Minds (http://www.lateralminds.com.au)
 * @version    $Id$
 * @license    New BSD License
 */

package com.lateralminds.alfresco.scripting;

import java.util.LinkedHashSet;
import java.util.List;

import javax.faces.context.FacesContext;

import org.alfresco.repo.jscript.BaseScopableProcessorExtension;
import org.alfresco.repo.jscript.ScriptNode;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

import com.lateralminds.alfresco.util.LateralService;

/**
 * Assorted utilities that are available from Alfresco server-side javascript
 * 
 * @author Marcus Nyeholt
 *
 */
public class LMUtils extends BaseScopableProcessorExtension
{

    /**
     * Performs a sorted search
     * 
     * @param search
     * @return
     */
    public Scriptable sortedSearch(String search, String sortProperty, String ascOrDesc)
    {
        if (search != null && search.length() != 0) {
            List<NodeRef> results = this.lateralService.searchForNodeRefs(search, sortProperty, ascOrDesc.equals("asc"));
            LinkedHashSet<ScriptNode> set = new LinkedHashSet<ScriptNode>();
            for (NodeRef nodeRef : results) {
                set.add(new ScriptNode(nodeRef, this.serviceRegistry, getScope()));
            }
            Object[] searchResults = set.toArray(new Object[(set.size())]);
            return Context.getCurrentContext().newArray(getScope(), searchResults);
        } else {
            return Context.getCurrentContext().newArray(getScope(), 0);
        }
    }
    
    public boolean exists(ScriptNode node)
    {
        return serviceRegistry.getNodeService().exists(node.getNodeRef());
    }

    public String context()
    {
        if (FacesContext.getCurrentInstance() != null) {
            return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        }
        
        return "";
    }

    private LateralService lateralService;
    private ServiceRegistry serviceRegistry;
    
    public void setLateralService(LateralService lateralService)
    {
        this.lateralService = lateralService;
    }
    
    public void setServiceRegistry(ServiceRegistry serviceRegistry)
    {
        this.serviceRegistry = serviceRegistry;
    }
}
